package xc.com.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xc.com.common.PageVo;
import xc.com.common.Result;
import xc.com.common.StatusCode;
import xc.com.manage.media.domain.MediaFile;
import xc.com.media.feign.OssFegin;
import xc.com.media.mapper.MediaFileMapper;
import xc.com.media.service.MediaFileService;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuolizhong
 * @since 2021-06-25
 */
@Service
public class MediaFileServiceImpl extends ServiceImpl<MediaFileMapper, MediaFile> implements MediaFileService {
    @Autowired
    private MediaFileMapper mediaFileMapper;
    @Autowired
    private OssFegin ossFegin;
    @Override
    public Result upload(MultipartFile file) {
        if(file==null){
            return new Result(false, StatusCode.FAIL,"没有获取到要上传的文件");
        }
        Map<String, Object> map = ossFegin.uploadMedia(file);
        MediaFile mediaFile=new MediaFile();
        mediaFile.setFileOriginalName(file.getOriginalFilename());
        mediaFile.setFilePath(String.valueOf(map.get("file_path")));
        mediaFile.setFileUrl(String.valueOf(map.get("file_url")));
        mediaFile.setFileType(  StringUtils.split(file.getOriginalFilename(), ".")[1]);
        mediaFile.setFileSize(file.getSize());
        mediaFile.setUploadTime(new Date());
        int insert = mediaFileMapper.insert(mediaFile);
        if(insert>0){
            return new Result(true, StatusCode.OK,"上传文件成功!");
        }
        return new Result(false, StatusCode.FAIL,"上传文件失败!");
    }

    @Override
    public PageVo<MediaFile> findList(Integer pageNum, Integer pageSize, MediaFile mediaFile) {
        PageVo<MediaFile> pageVo=new PageVo<>();
        QueryWrapper<MediaFile> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(mediaFile.getFileOriginalName())){
            queryWrapper.like("file_original_name",mediaFile.getFileOriginalName());
        }
            queryWrapper.eq("file_status",mediaFile.getFileStatus());
        Page<MediaFile> page= new Page<>(pageNum,pageSize);;
        Page<MediaFile> page1 = mediaFileMapper.selectPage(page, queryWrapper);
        pageVo.setRows(page1.getRecords());
        pageVo.setTotal(page1.getTotal());
        return pageVo;
    }
}
